package web

import (
	"fmt"
	"github.com/gookit/validate"
	"ksd-social-api/commons/base/controller"
	"ksd-social-api/modules/common/sms/contants"
	"ksd-social-api/modules/common/sms/context"
	"ksd-social-api/modules/common/sms/service"
	"ksd-social-api/utils/rdb"
)

type SMSController struct {
	controller.BaseController
}

var smsService = service.SMSService{}

/**
 * @author feige
 * @date 2023-10-09
 * @version 1.0
 * @desc  登录发送
 */
func (web *SMSController) SendPhoneCode() {
	// 1: 准备一个参数容器
	phoneContext := context.SMSPhoneContext{}
	// 2: 绑定参数
	web.BindJSON(&phoneContext)
	// 3: 对登录用户信息进行验证
	validation := validate.Struct(phoneContext)
	if !validation.Validate() {
		web.FailWithValidatorData(validation)
		return
	}

	// 5: 使用redis缓存进行数据共享
	cacheKey := fmt.Sprintf(contants.SMS_PHONE_KEY+"%s", phoneContext.Telephone)
	cacheCode, _ := rdb.RdbGet(cacheKey)
	if len(cacheCode) > 0 {
		web.FailCodeMsg(contants.SMS_PHONE_STATUS, contants.SMS_PHONE_LIMIT_TIME)
		return
	}
	// 4: 根据手机号码发送短信的接口
	sendCode, flag, err := smsService.SendPhone(phoneContext.Telephone)
	if flag {
		// 6: 丢入缓存中并设置时间
		rdb.RdbSetEX(cacheKey, sendCode, contants.SMS_PHONE_LIMIT_SECONDS)
		// 7: 返回发送是否成功
		web.Ok(sendCode)
	} else {
		web.FailData(err)
	}

}
